function getRoute(routetable,fd){
	
	var condition = true;
	var depth = 0;
	var xmlDocRouteTable;
	
	var xmlStr = routetable;
	if (window.DOMParser)
	{
		xmlDocRouteTable = new window.DOMParser().parseFromString(xmlStr, "text/xml");
	}
	else // code for IE
	{
		xmlDocRouteTable=new ActiveXObject("Microsoft.XMLDOM");
		xmlDocRouteTable.async=false;
		xmlDocRouteTable.loadXML(routetable);
	} 		
	
	var nbRoutes = 0;
	
	while(condition)
	{
		var tagName;
		var routes;
		var routesTable = [];
		if(depth == 0) {
			tagName = "direct";			
			routes = xmlDocRouteTable.getElementsByTagName(tagName);
			
			if(null != routes || routes.lenght > 0)
			{
				for (var i=0;i<routes.length;i++)
				{
					routesTable.push(routes[i].outerHTML);
					nbRoutes ++;
				}
			}
			else {break;}
		}
		else {
			tagName = "learn";
			routes = xmlDocRouteTable.getElementsByTagName(tagName);
			routes = Array.prototype.slice.call(routes);
			
			if(null != routes || routes.lenght > 0)
			{
				for (var i=0;i<routes.length;i++)
				{
					var attrdepth = routes[i].getAttribute('depth');
					if(attrdepth != depth)
					{
						routes.splice(i, 1);
						// routesTable.push(routes[i].outerHTML);
						i--;
					}
				}
				if(routes.length == 0){ condition = false; break;}
			}
			else { condition = false; break;}
		}
					
		for (var k=0;k<routes.length;k++)
		{
			var network = routes[k].getAttribute('network');
			var cost = routes[k].getAttribute('cost');
			var elementid = routes[k].getAttribute('id');
			var nexthop = routes[k].getAttribute('nexthop');			
			var nodeId = routes[k].getAttribute('nodeid');
			if(nodeId != null && nodeId != "" && nodeId != "undefined"){
				var node = fd.graph.nodes[nodeId];		
				var nodeAdjacencies = node.adjacencies;
			
				for(var id in nodeAdjacencies) {
					var a = nodeAdjacencies[id];	
					if(a.data.nodeFromMask !=  "undefined" && a.data.nodeFromIpAddress != "undefined" && a.data.nodeFromMask !=  null && a.data.nodeFromIpAddress != null)
					{
						var networkadj = getNetWorkAddress(a.data.nodeFromIpAddress,a.data.nodeFromMask);
						var costAdj = calculCost(a.data.bandwidth) + parseInt(cost);
						var routeState = a.data.ospfstate;
						var mask = getmaskprefix(a.data.nodeFromMask);
						
						if(networkadj != network && routeState == "up") {

							var allElements = xmlDocRouteTable.getElementsByTagName('*');
							var matchingElements = [];
							for (j = 0; j < allElements.length; j++)
							{
								if (allElements[j].getAttribute('network') == networkadj)
								{
									matchingElements.push(allElements[j]);
								}
							}
							if(matchingElements.length > 0)
							{
								var isOptimizedRoute = "true";
								for (j = 0; j < matchingElements.length; j++) {
									var costroute = parseInt(matchingElements[j].getAttribute('cost'));
									var networkfrom = matchingElements[j].getAttribute('networkfrom');
									if(costAdj > costroute)
									{
										isOptimizedRoute = "false";
									}
								}
								if(isOptimizedRoute == "true")
								{
									var nodeid;
									if(id == a.data.nodeFrom){
										nodeid = a.data.nodeFrom;
										// routerid = fd.graph.nodes[a.data.nodeTo].data.ospfRouterId;
									}
									else {
										nodeid = a.data.nodeTo;
										// routerid = fd.graph.nodes[a.data.nodeFrom].data.ospfRouterId;		
									}
									
									var divtest = document.createElement("learn");
									divtest.setAttribute('id', nbRoutes);
									divtest.setAttribute('network', networkadj);
									divtest.setAttribute('networkfrom', network);
									divtest.setAttribute('cost', costAdj);
									divtest.setAttribute('nexthop', nexthop);
									divtest.setAttribute('nodeid', nodeid);
									divtest.setAttribute('mask', mask);
									divtest.setAttribute('depth', depth + 1);
									divtest.innerHTML = "learn" + networkadj + " via " + nexthop + " cost: " + costAdj;
									
									xmlDocRouteTable.getElementById(elementid).appendChild(divtest);
							
									nbRoutes ++;
								}
							}
							else{						
								var nodeid;
								if(id == a.data.nodeFrom){
									nodeid = a.data.nodeFrom;
									// routerid = fd.graph.nodes[a.data.nodeTo].data.ospfRouterId;
								}
								else {
									nodeid = a.data.nodeTo;
									// routerid = fd.graph.nodes[a.data.nodeFrom].data.ospfRouterId;
								}

								var divtest = document.createElement("learn");
								divtest.setAttribute('id', nbRoutes);
								divtest.setAttribute('network', networkadj);
								divtest.setAttribute('networkfrom', network);
								divtest.setAttribute('cost', costAdj);
								divtest.setAttribute('nexthop', nexthop);
								divtest.setAttribute('nodeid', nodeid);
								divtest.setAttribute('mask', mask);
								divtest.setAttribute('depth', depth + 1);			
								divtest.innerHTML = "learn" + networkadj + " via " + nexthop + " cost: " + costAdj;
								
								xmlDocRouteTable.getElementById(elementid).appendChild(divtest);
								
								nbRoutes ++;							
							}
						}
					}
				}
			}
		}
		depth ++;
		// var rootNodeElement = xmlDocRouteTable.documentElement;	
		// var x = xmlDocRouteTable.getElementsByTagName(tagName);		
	}
	return xmlDocRouteTable;
}

function calculCost(bandwidth)
{
	var ospfCost = Math.pow(10,8)/bandwidth;
	return Math.floor(ospfCost);
}
function getRouterId(ospfRouterId,addressipvalue)
{
	if(addressipvalue == "undefined" || addressipvalue == null){return;}
	if(ospfRouterId == "" || ospfRouterId == null || ospfRouterId == "undefined")
	{
		return addressipvalue; 
	}
	else
	{
		var oldId = ospfRouterId.split(".");
		var newId = addressipvalue.split(".");
		
		for (i = 0; i < 4; i++) {
			var oldIdInt = parseInt(oldId[i]);
			var newIdInt = parseInt(newId[i]);
			if(newIdInt > oldIdInt)
			{
				return addressipvalue; 
			}
			else if(newIdInt < oldIdInt)
			{
				return ospfRouterId;
			}
		}
	}
}

function getNetWorkAddress(addressIp, mask)
{
	var addressIpTable = addressIp.split(".");
	var maskTable = mask.split(".");
	var results = "";
	if(maskTable.length == 4 && addressIpTable.length == 4)
	{
		for (i = 0; i < 4; i++) {
			var result = "";
			
			var intAddressIp = parseInt(addressIpTable[i]);
			var intmask = parseInt(maskTable[i]);
			
			if(isInt(intAddressIp) && isInt(intmask))
			{
				if( intAddressIp >= 0 && intAddressIp <= 255 && intmask >= 0 && intmask <= 255)
				{
					var binaryAddressIp = intAddressIp.toString(2);
					var binaryMask = intmask.toString(2);
					 
					binaryAddressIp = pad(binaryAddressIp,8)
					binaryMask = pad(binaryMask,8)
					
					if(binaryAddressIp.length == 8 && binaryMask.length == 8)
					{
						var binaryAddressIpTable = binaryAddressIp.split("");
						var binaryMaskTable = binaryMask.split("");
						
						for (j = 0; j < 8; j++) {
							var bitAddressIp = binaryAddressIpTable[j];
							var bitMask = binaryMaskTable[j];
							if( bitAddressIp == bitMask )
							{
								result += bitAddressIp;
							}
							else {result += 0;} 
						}
					}
					else { return "error"; }					
				}
				else { return "error"; }
			}
			else { return "error"; }
			
			results += parseInt(result, 2) + '.';
		}
		// var addressIpTable = num.toString(2);
	}
	else { return "error"; }
	return results.substring(0, results.length - 1);
}

function checkMask(mask){
	var maskTable = mask.split(".");
	for (i = 0; i < 4; i++) {
		var intmask = parseInt(maskTable[i]);
		if(intmask == 0 || intmask == 128 || intmask == 192 || intmask == 224 || intmask == 240 || intmask == 248 || intmask == 252 || intmask == 254 || intmask == 255 ){
			
		}
		else
		{
			return false;
		}
	}
	return true;
}
function getBroadcastAddress(networkAddress, mask)
{
	var networkAddressTable = networkAddress.split(".");
	var maskTable = mask.split(".");
	var result = "";
	for (i = 0; i < 4; i++) {
		
		var intnetwork = parseInt(networkAddressTable[i]);
		var intmask = parseInt(maskTable[i]);
		
		var sum = intnetwork + (255 - intmask);
		
		result += sum + '.';
	}
	return result.substring(0, result.length - 1);
}

function getIpRouteTable(database){
	var tablenetdest = [];
	var allxml = database.getElementsByTagName("*");
	var tableIpRoute = "";
	var tableIpRouteDir = "";
	for (var m = 0; m < allxml.length; m++){
		var net = allxml[m].getAttribute('network');
		if(null != net){
			var isNet = "false";
			for(var n = 0; n < tablenetdest.length; n++){
				if(tablenetdest[n] == net){isNet = "true";break;}
			}
			if(isNet=="false"){tablenetdest.push(net);}
		}
	}
	for(var n = 0; n < tablenetdest.length; n++){
		var compteur = 0;
		for (var m = 0; m < allxml.length; m++){
			if(allxml[m].getAttribute('network') == tablenetdest[n]){
				var network = allxml[m].getAttribute('network'); 
				var cost = allxml[m].getAttribute('cost'); 
				var nexthop = allxml[m].getAttribute('nexthop');
				var mask = allxml[m].getAttribute('mask');
				var nodeName = allxml[m].nodeName;
				if(nodeName == "direct"){
					tableIpRouteDir += toHTML(nodeName,"strong") + " => " + network + "/" + toCSSColor(mask,"blue") + "<br>";
				} else if(nodeName == "learn"){
					if(compteur==0){
						tableIpRoute += toHTML(nodeName,"strong") + " => " + network + "/" + toCSSColor(mask,"blue") +" via "+ nexthop + " cost: " + toCSSColor(cost,"orange") + "<br>";
					} else {
						var whitespacel = nodeName + " => " + network + "/" + mask;
						whitespacel = whitespacel.length;
						var whitespace = "";
						for (var w=0;w<whitespacel;w++){whitespace+= "&nbsp;&nbsp;";}
						tableIpRoute += whitespace + " via "+ nexthop + " cost: " + toCSSColor(cost,"orange") + "<br>";
					}
					compteur++;
				}
			}
		}
	}
	return tableIpRouteDir + tableIpRoute;
}

function getmaskprefix(mask){
	var masktable = mask.split(".");
	var prefixvalue = 0;
	for(var m = 0;m<4;m++){
		switch(masktable[m]) {
			case "255":
				prefixvalue += 8;
				break;
			case "254":
				prefixvalue += 7;
				break;
			case "252":
				prefixvalue += 6;
				break;
			case "248":
				prefixvalue += 5;
				break;
			case "240":
				prefixvalue += 4;
				break;
			case "224":
				prefixvalue += 3;
				break;
			case "192":
				prefixvalue += 2;
				break;
			case "128":
				prefixvalue += 1;
				break;
			case "0":
				prefixvalue += 0;
				break;
			// default:
				// default throw "error";
		}
	}
	return prefixvalue;
}

function getmaskfromprefix(prefix){
	
	var prefixvalue = parseInt(prefix);
	var entier = Math.floor(prefixvalue / 8);
	var reste = prefixvalue % 8;
	var valuereturn = "";
	
	for(var m = 0;m<entier;m++){
		valuereturn += "255."
	}
	if(entier < 4){
		if(reste == 0){valuereturn += "0."}
		else if(reste == 1){valuereturn += "128."}
		else if(reste == 2){valuereturn += "192."}
		else if(reste == 3){valuereturn += "224."}
		else if(reste == 4){valuereturn += "240."}
		else if(reste == 5){valuereturn += "248."}
		else if(reste == 6){valuereturn += "252."}
		else if(reste == 7){valuereturn += "254."}
	}
	for(var m = 0;m< 4 - entier - 1 ;m++){
		valuereturn += "0."
	}
	return valuereturn.substring(0, valuereturn.length - 1);
}

function pad(num, size) {
    var s = num+"";
    while (s.length < size) s = "0" + s;
    return s;
}
function isInt(n){
    return typeof n== "number" && isFinite(n) && n%1===0;
}

function toHTML(str,balise){
	return "<"+balise+">"+str +"</"+balise+">";
}
function toCSSColor(str,color){
	return '<span style= color:' + color + '; >' + str + '</span>';
}
